/*
* Copyright (C) Microsoft. All rights reserved.  
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not 
* use this file except in compliance with the License.  You may obtain a copy 
* of the License at http://www.apache.org/licenses/LICENSE-2.0  
* 
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
* WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
* MERCHANTABLITY OR NON-INFRINGEMENT. 
*
* See the Apache License, Version 2.0 for specific language governing 
* permissions and limitations under the License.
*
*/
#include "pch.h"
#include <journal/models/page_model_factory.h>
#include <journal/models/db/page_table.h>
#include <journal/models/page_model.h>

using namespace journal::model;

b::uint32 page_model_factory::_typeToken = 0;

page_model_factory::page_model_factory(std::shared_ptr<s::iengine> dbEngine) :
    _nextId(0),
    _dbEngine(dbEngine)
{
    if (_typeToken == 0)
    {
        _typeToken = constants::undoRedoService()->generateTargetTypeToken();

        constants::memoryTrackingService()->registerType(_typeToken, L"page model", true);

        DEBUG_CONSOLE_TRACE_TAG(TRACE_TAG_GENERIC_MODEL,
            boost::wformat(L"page_model_factory::page_model_factory() : type token = %i") %
            _typeToken
            );
    }
}

void page_model_factory::getPersistedPageIds(std::vector<b::uint32>& ids)
{
    _pageTable->readIds(ids);
}

std::shared_ptr<ipage_model_factory> page_model_factory::create(std::shared_ptr<s::iengine> dbEngine)
{
    static bool instantiated = false;
    static std::shared_ptr<page_model_factory> returnValue = std::make_shared<page_model_factory>(dbEngine);
    static std::recursive_mutex mutex;
    BAJA_LOCK(mutex);
    if (instantiated == false)
    {
        returnValue->_pageTable = journal::model::db::createPageTable(dbEngine);
        returnValue->_pageTable->common()->initialize();
        returnValue->_nextId = returnValue->_pageTable->common()->getNextId();
        instantiated = true;
    }
    return returnValue;
}

b::uint32 page_model_factory::typeToken()
{
    return _typeToken;
}

std::shared_ptr<ipage_model> page_model_factory::createPage(
    const std::shared_ptr<inotebook_model>& parent)
{
    return journal::model::createPageModel(_typeToken, parent, _pageTable, _nextId++);
}

std::shared_ptr<ipage_model> page_model_factory::recreatePage(
    const std::shared_ptr<inotebook_model>& parent, 
    const b::uint32 pageId)
{
    return journal::model::createPageModel(_typeToken, parent, _pageTable, pageId);
}

std::shared_ptr<ipage_model_factory> journal::model::createPageModelFactory(std::shared_ptr<s::iengine> dbEngine)
{
    return page_model_factory::create(dbEngine);
}
